<template>
  <div class="table-container">
    <Problem>
      <template v-slot:custom-slot>
        <el-button size="small" type="primary" @click="handleAdd">添加题目</el-button>
        <el-button size="small" type="primary" @click="handleTag">添加标签</el-button>
        <el-button size="small" type="primary" @click="handleGroup">添加题组</el-button>
        <el-button size="small" type="primary" @click="addTestGroup">生成测试集</el-button>
      </template>
      <template v-slot:actions="{ row }">
        <el-button type="primary" size="small" @click="(event) => editRow(row, event)">编辑</el-button>
        <!-- 动态按钮文本和颜色 -->
        <el-button
            :type="row.isBan === 0 ? 'danger' : 'success'"
            size="small"
            @click="(event) => toggleRowStatus(row, event)"
        >
          {{ row.isBan === 0 ? '禁用' : '恢复' }}
        </el-button>
      </template>
    </Problem>
  </div>
</template>


<script lang="ts" setup>
import router from "@/router";
import Problem from "@/components/ProblemLib/Promblem.vue";
import { API_BASE_URL, AUTH_TOKEN } from "@/config.ts";
import axios from "axios";

// 处理添加题目的函数
const handleAdd = () => {
  router.push('/UploadProblem');
};

// 处理编辑问题的函数
const editRow = (row, event) => {
  event.stopPropagation();  // 阻止事件冒泡

  const plainRow = JSON.parse(JSON.stringify(row));
  console.log(plainRow);

  router.push({
    path: '/UploadProblem',
    query: {
      editing: 1,
      id: plainRow.id,
      title: plainRow.title,
      description: plainRow.description,
      difficulty: plainRow.difficulty,
      tags: JSON.stringify(plainRow.tags),
      codeId: plainRow.codeId,
      isBan: plainRow.isBan,
      commitNum: plainRow.commitNum,
      passNum: plainRow.passNum
    }
  });
};


const addTestGroup = () => {
  router.push('/generateTestGroup');
};

// 切换题目状态的函数
const toggleRowStatus = async (row, event) => {
  event.stopPropagation();  // 阻止事件冒泡

  try {
    // 确定操作的 URL，根据当前 isBan 值来决定禁用还是恢复
    const actionUrl = `${API_BASE_URL}/ProblemsGroup/problems/${row.isBan === 0 ? 'ban' : 'active'}/${row.id}`;
    const actionResponse = await axios.get(actionUrl, {
      headers: {
        'token': AUTH_TOKEN
      }
    });

    if (actionResponse.data.code === 0) {
      // 更新本地 row 的 isBan 值，反映状态变化
      row.isBan = row.isBan === 0 ? 1 : 0;
      alert(row.isBan === 1 ? "禁用成功" : "恢复成功");
    } else {
      alert(row.isBan === 0 ? "禁用失败" : "恢复失败");
    }
  } catch (error) {
    console.error("操作失败", error);
    alert("操作失败，请稍后重试");
  }
};
</script>

<style scoped>
.table-container {
  width: 100%;
  margin-top: 1.2vh;
}
</style>
